package com.vnt.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 权限验证过滤器
 */
@Component
public class AccessFilter extends ZuulFilter {
    public AccessFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
   }

    @Override
    public Object run() throws ZuulException {
        // 获取请求上下文
        RequestContext rc = RequestContext.getCurrentContext();
        HttpServletRequest request = rc.getRequest();
        // 获取表单中的 token
        String token = request.getParameter("token");
        // 业务逻辑处理
        if(null==token){
            System.out.println("token is null");
            ReturnError(rc);
        }
        // 使用 token 进行身份呢验证
        System.out.println(token);
        try{
            Claims claims = Jwts.parser()
                    .setSigningKey("1234") // 使用秘钥验证 token 的有效性
                    .parseClaimsJws(token)
                    .getBody();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date issuedAt = claims.getIssuedAt();

        }catch(JwtException j){
            // 请求结束,不在继续向下请求
            System.out.println("token 过期");
            ReturnError(rc);
        }

        return null;
    }

    private void ReturnError(RequestContext rc){
        // 请求结束,不在继续向下请求
        rc.setSendZuulResponse(false);
        // 相应状态码, HTTP 401 错误代表用户没有访问权限
        rc.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        // 响应类型
        rc.getResponse().setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        try{
            writer=rc.getResponse().getWriter();
            // 响应内容
            writer.println("{\"message\":\"" + HttpStatus.UNAUTHORIZED.getReasonPhrase() + "\"}");
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if(null != writer){
                writer.close();
            }
        }
    }
}
